package com.gec.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
@Slf4j
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("JdbcUserDetailsService")
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        log.info("=========configure HttpSecurity========");
        http.authorizeRequests()
                .antMatchers("/index", "/mylogin", "/login", "/error")
                .permitAll()  //放行/index路径
                .antMatchers("/access/user/**")
                .hasRole("USER")  //访问/access/user/**路径需要USER角色
                .antMatchers("/access/read/**")
                .hasRole("READ")  //访问/access/read/**路径需要READ角色
                .antMatchers("/access/admin/**")
                .hasRole("ADMIN")  //访问/access/admin/**路径需要ADMIN角色
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/mylogin")  //自定义登录页面的地址
                .loginProcessingUrl("/login") //自定义登录页面的登录跳转地址
                .failureUrl("/error")  //自定义登录验证错误的提示页面
                .and()
                .logout()
                .permitAll();
    }
}
